package lucene;

import java.util.HashSet;
import java.util.List;

import org.apache.lucene.analysis.standard.StandardAnalyzer;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field.Store;
import org.apache.lucene.document.StringField;
import org.apache.lucene.document.TextField;
import org.apache.lucene.index.Term;
import org.apache.lucene.queryparser.classic.QueryParser;
import org.apache.lucene.search.Query;

import cc.dullsky.lucene.model.ConfigBean;
import cc.dullsky.lucene.model.IndexConfig;
import cc.dullsky.lucene.model.SearchResultBean;
import cc.dullsky.lucene.operation.IndexOperation;
import cc.dullsky.lucene.operation.IndexSearch;

public class lucene {
	public static void main(String[] args) {
		try {
			HashSet<ConfigBean> set = new HashSet<ConfigBean>();
			ConfigBean configBean = new ConfigBean();
			configBean.setIndexPath("D:/dullskyIndex");
			configBean.setIndexName("dullsky");
			set.add(configBean);
			IndexConfig.setConfig(set);
			String indexName = "dullsky";
			IndexOperation index = new IndexOperation(indexName);
			Document doc = new Document();
			doc.add(new StringField("id", "1", Store.YES));
			doc.add(new TextField("content", "dullsky欢迎进入我的世界", Store.YES));
			index.addDocument(doc);
			doc = new Document();
			doc.add(new StringField("id", "2", Store.YES));
			doc.add(new TextField("content", "xor啦啦啦", Store.YES));
			index.addDocument(doc);
			index.commit();
			System.out.println("已向索引添加两条记录");
			IndexSearch search = new IndexSearch(indexName);
			QueryParser parser = new QueryParser("content", new StandardAnalyzer());
			Query query = parser.parse("dullsky");
			SearchResultBean bean = search.search(query, 0, 10);
			List<Document> documents = bean.getDocs();
			for (Document document : documents) {
				System.out.println(document.get("id"));
				System.out.println(document.get("content"));
			}
			System.out.println("第一次查询" + bean.getCount());
			doc = new Document();
			doc.add(new StringField("id", "2", Store.YES));
			doc.add(new TextField("content", "", Store.YES));
			Term term = new Term("id", "2");
			index.updateDocument(term, doc);
			index.commit();
			System.out.println("第一次修改一条记录");
			bean = search.search(query, 0, 10);
			System.out.println("第二次查询" + bean.getCount());

		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
